package com.pansoft.xmlparse;

import com.efounder.service.Registry;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

import java.util.List;

/**
 * 解析Mobile_FMT文件工具
 *
 * @author long
 * 2015-3-14 14:51:51
 */
public class MobileFormatUtil {
    private FormatSet formatSet;
    private volatile static MobileFormatUtil mInstance;
    /**
     * 是否已经检查过
     */
    private boolean hasChecked;


    public static MobileFormatUtil getInstance() {
        if (mInstance == null) {
            synchronized (MobileFormatUtil.class) {
                if (mInstance == null) {
                    mInstance = new MobileFormatUtil();
                }
            }
        }
        return mInstance;
    }

    public static void release() {
        mInstance = null;
    }

    private MobileFormatUtil() {
        formatSet = new FormatSet();
    }


    public FormatSet getFormatSet() {
        checkFormatSet();
        return formatSet;
    }


    /**
     * 解析Mobile_FMT 节点
     * 通过反射调用
     */
    public void parseXML(Element fmtElement) {
        try {
            parseXMlNode(fmtElement);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parseXMlNode(Node rootNode) throws Exception {
        String id = ((Element) rootNode).getAttribute("id");
        if ("mobile_fmt".equals(id)) {
            FormatParse.xml2FormatSet(formatSet, rootNode);
        }
    }


    //执行检查，因为如果单例类被回收，创建的formatSet 里面的list 数组大小为0
    private void checkFormatSet() {

        if (hasChecked) {
            return;
        }
        if (formatSet.getTableList().size() == 0) {
            formatSet = new FormatSet();
            List<Element> elementList = Registry.getFmtElement();
            for (int i = 0; i < elementList.size(); i++) {
                try {
                    parseXML(elementList.get(i));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        hasChecked = true;
    }

}
